using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using Geekees.App.Cashbook.Lib;
using Geekees.App.Cashbook.Lib.BLL;
using Geekees.App.Cashbook.Lib.Entity;
using Geekees.App.Cashbook.Lib.Helper;

namespace Geekees.App.Cashbook.Web
{
	/// <summary>
	/// Summary description for Statistics.
	/// </summary>
	public class Statistics : PageBase
	{
		protected System.Web.UI.WebControls.Repeater rptCashItem;
		protected System.Web.UI.WebControls.Literal lTotalIncome;
		protected System.Web.UI.WebControls.Literal lTotalOutcome;
		protected System.Web.UI.WebControls.Button btnSearch;
		protected System.Web.UI.WebControls.Literal lDifference;
		protected System.Web.UI.WebControls.Image imgCategoryBarChart;
		protected System.Web.UI.WebControls.Image imgClassificationBarChart;
		protected System.Web.UI.WebControls.Image imgTypePieChart;

		protected Geekees.App.Cashbook.Web.Controls.SearchDashboard sdSearchDashboard; 
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			if(!IsPostBack )
			{
				BindData();
			}
		}

		private void BindData()
		{
			DataTable dt = this.GetDataSource();//BLCashItem.GetAllCashItem();
			

			string barChartClassificationUrl = GetBarChartUrl( dt, "Amount", "ClassificationName", 100, "885111", "00aa00", "bvg" );
			this.imgClassificationBarChart.ImageUrl = barChartClassificationUrl;

			string barChartCategoryUrl = GetBarChartUrl( dt, "Amount", "CategoryName", 50, "285ACC", "00aa00", "bvg" );
			this.imgCategoryBarChart.ImageUrl = barChartCategoryUrl;
			
			string pieChartTypeUrl = GetPieChartUrl( dt, "Amount", "Type", 50, "F89327", "108F07", "p3" );
			this.imgTypePieChart.ImageUrl = pieChartTypeUrl;

			float totalIncome = 0F;
			float totalOutcome = 0F;
			foreach( DataRow dr in dt.Rows )
			{
				float amount = float.Parse( dr["Amount"].ToString() );
				int t = (int)dr["Type"];
				if( t == (int)CashItemType.Outcome )
					totalOutcome += amount;

				if( t == (int)CashItemType.Income )
					totalIncome += amount;
			}

			this.lTotalIncome.Text = totalIncome.ToString();
			this.lTotalOutcome.Text = totalOutcome.ToString();
			this.lDifference.Text = ( totalIncome - totalOutcome ).ToString();

			this.rptCashItem.DataSource = dt;
			this.rptCashItem.DataBind();
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
			this.rptCashItem.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.rptCashItem_ItemDataBound);
			this.rptCashItem.ItemCommand += new System.Web.UI.WebControls.RepeaterCommandEventHandler(this.rptCashItem_ItemCommand);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void rptCashItem_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			DataRowView drv = e.Item.DataItem as DataRowView;
			if( drv == null )
				return;

			Literal lId = e.Item.FindControl("lId") as Literal;
			Literal lDate = e.Item.FindControl("lDate") as Literal;
			Literal lClassification = e.Item.FindControl("lClassification") as Literal;
			Literal lCategory = e.Item.FindControl("lCategory") as Literal;
			Literal lAmount = e.Item.FindControl("lAmount") as Literal;
			Literal lDetail = e.Item.FindControl("lDetail") as Literal;
			Literal lType = e.Item.FindControl("lType") as Literal;

			LinkButton lbEdit =e.Item.FindControl("lbEdit") as LinkButton;
			LinkButton lbDelete =e.Item.FindControl("lbDelete") as LinkButton;
			lbDelete.Attributes.Add("onclick", "return confirm('Sure?');");

			lId.Text = drv["Id"].ToString();
			lDate.Text = ((DateTime)drv["CreateTime"]).ToString("MM-dd");
			lClassification.Text = drv["ClassificationName"].ToString();
			lCategory.Text = drv["CategoryName"].ToString();
			lAmount.Text = drv["Amount"].ToString();
			lDetail.Text = drv["Detail"].ToString();

			#region get type
			int t = (int)drv["Type"];
			string strType = string.Empty;
			if( t == (int)CashItemType.Outcome )
				strType = "Out";

			if( t == (int)CashItemType.Income )
				strType = "In";
			lType.Text = strType;
			#endregion			
		}

		private void rptCashItem_ItemCommand(object source, RepeaterCommandEventArgs e)
		{

			Literal lId = e.Item.FindControl("lId") as Literal;
			int id = int.Parse(lId.Text.ToString());

			if( e.CommandName.ToLower() == "edit")
			{
				Response.Redirect( string.Format( "Cashbook.aspx?action=edit&id={0}", id ) );
			}

			if( e.CommandName.ToLower() == "delete")
			{
				if( BLCashItem.DeleteCashItem( id ) )
					FlashMessage.SetFlash( "Delete Successful!" );
				else
					FlashMessage.SetFlash( "Delete Failed!" , FlashMessage.FlashMessageType.Error);

				BindData();
			}
		}

		private void btnSearch_Click(object sender, System.EventArgs e)
		{
			BindData();
		}

		private DataTable GetDataSource()
		{
			this.sdSearchDashboard.GetValue();

			DateTime fromDate = this.sdSearchDashboard.FromDate;
			DateTime toDate = this.sdSearchDashboard.ToDate;

			int classificationId = this.sdSearchDashboard.ClassificationId;
			int categoryId = this.sdSearchDashboard.CategoryId;

			CashItemType itemType = this.sdSearchDashboard.ItemType;
			OrderByType orderType = this.sdSearchDashboard.OrderType;

			return BLCashItem.SearchCashItem( fromDate, toDate, classificationId, categoryId, itemType, orderType );
		}


		public static string GetBarChartUrl( DataTable dt, string dataColumn, string presentationColumn, int barWidth, string color1, string color2, string type )		{			Hashtable ht = new Hashtable();			foreach( DataRow dr in dt.Rows )
			{				string strCategory = (string)dr[presentationColumn];				float fCur = float.Parse( dr["Amount"].ToString() );				if( ht[strCategory] != null )				{					float f = (float)ht[strCategory];					ht[strCategory] = fCur + f;				}				else					ht[strCategory] = fCur;			}			float fMax = 0;			foreach( string k in ht.Keys )
			{
				float fCur = ( float )ht[k];
				if( fCur > fMax)
					fMax = fCur;
			}			string strData = string.Empty;			string strXL0 = string.Empty;			foreach( string k in ht.Keys )
			{				float fCur = ( float )ht[k];
				float fDisp = ( fCur * 100 / fMax );
				string strDisp = fDisp.ToString("0.00");
				strData += ( strDisp + "," );				string strCur = k;				strCur = strCur.Replace( "|" , "" );				foreach( char c in strCur )				{
					int iAscii = (int)c;
					if( !( ( iAscii > 64 && iAscii < 91 ) || ( iAscii > 96 && iAscii < 123 ) || char.IsDigit(c) ) )
						strCur = strCur.Replace( c.ToString(), "" );
				}				strXL0 += ( strCur + "|" );			}				if( strData.EndsWith( "," ) )					strData = strData.Substring( 0, strData.Length - 1 );						if( strXL0.EndsWith( "|" ) )				strXL0 = strXL0.Substring( 0, strXL0.Length - 1 );						//get xl1			string strXL1 = string.Empty;			float f1 = fMax;			float f2 = fMax / 4 * 3;			float f3 = fMax / 4 * 2;			float f4 = fMax / 4;			strXL1 = "0|" + f4.ToString("0.00") + "|" + f3.ToString("0.00") + "|" + f2.ToString("0.00") + "|" + f1.ToString( "0.00" );//00aa00 bvg			string url = string.Format("http://chart.apis.google.com/chart?chs=980x300&chbh={3},50&cht={6}&chco={4},{5}&chd=t:{0}&chxt=x,y&chxl=0:|{1}|1:|{2}", strData, strXL0, strXL1, barWidth, color1, color2, type );			//http://chart.apis.google.com/chart?chs=300x200&cht=bvg&chco=cc0000,00aa00&chd=t:1,2,3|4,5,100&chxt=x,y&chxl=0:|in,in|out|income|income|income|income|1:|0|50|100			return url;		}


		/// <summary>
		/// pie chart
		/// </summary>
		/// <param name="dt"></param>
		/// <param name="dataColumn"></param>
		/// <param name="presentationColumn"></param>
		/// <param name="barWidth"></param>
		/// <param name="color1"></param>
		/// <param name="color2"></param>
		/// <param name="type"></param>
		/// <returns></returns>
		public static string GetPieChartUrl( DataTable dt, string dataColumn, string presentationColumn, int barWidth, string color1, string color2, string type )		{			Hashtable ht = new Hashtable();			foreach( DataRow dr in dt.Rows )
			{				//string strCategory = (int)dr[presentationColumn];				int iType = (int)dr[presentationColumn];				string strCategory = iType == 1 ? "Outgoings" : "Income";				float fCur = float.Parse( dr["Amount"].ToString() );				if( ht[strCategory] != null )				{					float f = (float)ht[strCategory];					ht[strCategory] = fCur + f;				}				else					ht[strCategory] = fCur;			}			float fMax = 0;			foreach( string k in ht.Keys )
			{
				float fCur = ( float )ht[k];
				if( fCur > fMax)
					fMax = fCur;
			}			string strData = string.Empty;			string strXL0 = string.Empty;			foreach( string k in ht.Keys )
			{				float fCur = ( float )ht[k];
				float fDisp = ( fCur * 100 / fMax );
				string strDisp = fDisp.ToString("0.00");
				strData += ( strDisp + "," );				string strCur = k;				strCur = strCur.Replace( "|" , "" );				foreach( char c in strCur )				{
					int iAscii = (int)c;
					if( !( ( iAscii > 64 && iAscii < 91 ) || ( iAscii > 96 && iAscii < 123 ) || char.IsDigit(c) ) )
						strCur = strCur.Replace( c.ToString(), "" );
				}				strXL0 += ( strCur + "|" );			}				if( strData.EndsWith( "," ) )					strData = strData.Substring( 0, strData.Length - 1 );						if( strXL0.EndsWith( "|" ) )				strXL0 = strXL0.Substring( 0, strXL0.Length - 1 );						//get xl1			string strXL1 = string.Empty;			float f1 = fMax;			float f2 = fMax / 4 * 3;			float f3 = fMax / 4 * 2;			float f4 = fMax / 4;			strXL1 = "0|" + f4.ToString("0.00") + "|" + f3.ToString("0.00") + "|" + f2.ToString("0.00") + "|" + f1.ToString( "0.00" );			//00aa00 bvg			string url = string.Format("http://chart.apis.google.com/chart?chs=980x300&chbh={3},50&cht={6}&chco={4},{5}&chd=t:{0}&chxt=x,y&chxl=0:|{1}|1:|{2}", strData, strXL0, strXL1, barWidth, color1, color2, type );			//http://chart.apis.google.com/chart?chs=300x200&cht=bvg&chco=cc0000,00aa00&chd=t:1,2,3|4,5,100&chxt=x,y&chxl=0:|in,in|out|income|income|income|income|1:|0|50|100			return url;		}
	}
}
